import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入vuex实例=>store === 页面中的this.$store
import store from '../store'

// 按需导入路由组件（懒加载）
// 布局组件(一)=》布局组件（公共的头部+router-view（二级路由挂载点）+菜单）
const Layout = () => import('@/views/layout.vue')
// 首页（第一个标签页）=》二级路由
const Index = () => import('@/views/home/index.vue')
// 问答
const Question = () => import('@/views/question/index.vue')
// 视频
const Video = () => import('@/views/video/index.vue')
// 个人中心
const Profile = () => import('@/views/profile/index.vue')
// end
// 登录
const Login = () => import('@/views/login/index.vue')
// 编辑个人资料
const User = () => import('@/views/user/edit.vue')
// 小智
const Chat = () => import('@/views/user/chat.vue')
// 搜索
const Search = () => import('@/views/search/index.vue')
const Result = () => import('@/views/search/result.vue')
// 详情
const Article = () => import('@/views/article/index.vue')

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    // 布局骨架
    component: Layout,
    // 二级路由
    children: [
      {
        path: '/',
        name: 'index',
        // 首页
        component: Index,
        meta: {
          // 开启缓存
          isKeepAlive: true
        }
      },
      {
        path: '/question',
        name: 'question',
        // 问答
        component: Question
      },
      {
        path: '/video',
        name: 'video',
        // 视频
        component: Video
      },
      {
        path: '/user',
        name: 'user',
        // 个人中心
        component: Profile
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    // 登录
    component: Login
  },
  {
    path: '/user/profile',
    name: 'profile',
    // 编辑资料
    component: User
  },
  {
    path: '/user/chat',
    name: 'chat',
    // 小智同学
    component: Chat
  },
  {
    path: '/search',
    name: 'search',
    // 搜索
    component: Search
  },
  {
    path: '/search/result',
    name: 'result',
    // 搜索结果
    component: Result
  },
  {
    path: '/article/:id',
    name: 'article',
    // 文章详情
    component: Article,
    meta: {
      // 开启缓存
      isKeepAlive: true
    }
  }
]

const router = new VueRouter({
  routes
})

// 添加前门保安=》需求：控制'/user'开头的页面需要有token才能访问，如果没有跳转到登录
/**
 * to 去哪
 * form 从哪来
 * next（方法）放行
 */
router.beforeEach((to, from, next) => {
  const { user } = store.state
  if (to.path.startsWith('/user') && !user.token) {
    // 是用户相关页面，没有token(只是判断是否有token值，没有判断token真假和是否失效)
    // next === router.push 一样也可以跳转页面
    // 需求：把用户当前访问的没登录页面path当做参数（to.path），带到登录页=>登录成功后，跳到上次访问的页面
    next(`/login?redirectUrl=${to.path}`)
  } else {
    next()
  }
})

export default router
